<?php
namespace Home\Controller;

use Think\Controller;

class IndexController extends Controller
{
//    public function _initialize()
//    {
//        $table_name = "siteinfo_" . date("Ymd", time());
//        $this->db = M($table_name);
//
//    }

    //写入数据库
    public function index()
    {
        header("Access-Control-Allow-Origin: *");
        if (I('url')) {
            //接收传过来的数据
            $data['url'] = $url = I('url');
            $data['title'] = $title = I('title');
            $data['description'] = $description = I('description');
            $data['keywords'] = $keywords = I('keywords');
            $refer = I('refer');
            $data['createtime'] = date("Ymd", time());

            /**方法一**/
            //如果url不为空，则计算url的murmurhash值,哈希索引用于判断该url是否已经存入到数据库
            if (!empty($url)) {
                //传给夏雨，让他好判断
                header('Content-Type:application/json; charset=utf-8');
                $return_data['status'] = 1;
                echo json_encode($return_data);
                echo I('jsonp')."({'ret':'true'})";

                $pos = strpos($url, "?");
                if ($pos !== false) { //表明url存在带问号的参数,则去掉url中？后面的部分求 hash
                    $pos2 = substr($url, $pos);
                    $url1 = str_replace($pos2, "", $url);
                }else{
                    $url1=$url;//如果不带问号，则url1就是url
                }
                $data['hash_url'] = $hash_url = $this->murmurhash3_int($url1, 7);
//                $where['hash_url'] = $hash_url;
//                $res = $this->db->where($where)->find();

                /**************使用redis缓存hash_url，作为判断当前url是否已经存在的方法********************/
                $redis = new \Redis;
                $redis->connect('127.0.0.1', 6379);

                //先检查昨天的key是否存在，存在的话，就删除
                $pre_set = date("Ymd", time() - 86400) . "_hash_url";
                $ex = $redis->exists($pre_set);//返回值：false/true
                if ($ex) {
                    $redis->delete($pre_set);
                }

                $set = date("Ymd", time()) . "_hash_url";
                $res = $redis->sAdd($set, $hash_url);//返回值：1/0
            }
            //redis集合的特性：集合元素保持唯一，如元素存在则无法写入并返回0，可以写入则返回1
            if ($res) { //表明该记录不存在，则写入数据库
                if (!empty($title) || !empty($description) || !empty($keywords)) {
                    $data['num'] = 1;
                    // G('begin');
                    $rid = $this->db->data($data)->add();
                    // G('end');
                    // $m=G('begin','end').'s';
                    // file_put_contents('./m_add.txt',$m.PHP_EOL,FILE_APPEND);
                    //出错则将错误信息保存到日志
                    if ($rid === false) {
                        $error = M($this->db)->getDbError();
                        $error = "【" . date("Y-m-d H:i:s", time()) . "】" . $error;
//                        file_put_contents('./error.log', $error . PHP_EOL, FILE_APPEND);
                    }
                }
            } else {
//                G('begin');
                //如果该url已经存在，刚将该条记录的值加1
                $map['hash_url'] = $hash_url;
//                $this->db->where($map)->setInc('num', 1);
//                G('end');
//                $m=G('begin','end').'s';
//                file_put_contents('./m.txt',$m.PHP_EOL,FILE_APPEND);
            }
//            /**方法二**/
//            if (!empty($title) || !empty($description) || !empty($keywords)) {
//                if(strlen($url)>333) die;
//                $data['num'] = 1;
//                $rid = $this->db->data($data)->add();
//                if($rid===false){
//                    $error = $this->db->getDbError();
////                    $error = "【" . date("Y-m-d H:i:s", time()) . "】" . $error;
////                    file_put_contents('./error.log', $error . PHP_EOL, FILE_APPEND);
//                    $error_code="1062:Duplicate entry";
//                    if(strpos($error,$error_code)===0){ //表明url是重复值
//                        $map['url']=$url;
//                        $this->db->where($map)->setInc('num', 1);
//                    }
//                }
//            }
        }
    }

    public function test()
    {

    }


    // 列表展示
    // public function lst()
    // {
    //     if (IS_GET) {
    //         $keyword = I('keyword', '', 'trim');
    //         if (!empty($keyword)) {
    //             $like = "%$keyword%";
    //             $where['title'] = array('like', $like);
    //             $where['description'] = array('like', $like);
    //             $where['keywords'] = array('like', $like);
    //             $where['url'] = array('like', $like);
    //             $where['_logic'] = 'or';

    //             $this->assign('keyword', $keyword);
    //         }

    //         $date = I('date');
    //         if (!empty($date)) {
    //             $table_name = "siteinfo_" . date("Ymd", strtotime($date));
    //             $this->db = M($table_name);
    //         }
    //     } else {
    //         $where = array();
    //     }

    //     //分页实现
    //     $count = $this->db->where($where)->count();
    //     $num = 100;//每页显示的条数

    //     $page_c = new \Think\Page($count, $num);
    //     $page = $page_c->show();
    //     $lists = $this->db->where($where)->order("num desc,id desc")->limit($page_c->firstRow . ',' . $page_c->listRows)->select();

    //     $this->assign('page', $page);
    //     $this->assign('count', $count);
    //     $this->assign('lists', $lists);

    //     $this->display();
    // }

    //服务器上有定时任务，每天复制一张以当天第二天日期
    public function copy_siteinfo()
    {
        $table_name = "siteinfo_" . date("Ymd", time() + 86400);
        $sql = "create table if not EXISTS $table_name like origin";
        $res = $this->db->execute($sql);
        if ($res === false) {
            $error = $this->db->getDbError();
            $error = "【" . date("Y-m-d H:i:s", time()) . "】" . $error;
            file_put_contents('./copy_error.log', $error . PHP_EOL, FILE_APPEND);
        }
    }

    public function murmurhash3_int($key, $seed = 0)
    {
        $key = array_values(unpack('C*', (string)$key));
        $klen = count($key);
        $h1 = (int)$seed;
        for ($i = 0, $bytes = $klen - ($remainder = $klen & 3); $i < $bytes;) {
            $k1 = $key[$i]
                | ($key[++$i] << 8)
                | ($key[++$i] << 16)
                | ($key[++$i] << 24);
            ++$i;
            $k1 = (((($k1 & 0xffff) * 0xcc9e2d51) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0xcc9e2d51) & 0xffff) << 16))) & 0xffffffff;
            $k1 = $k1 << 15 | ($k1 >= 0 ? $k1 >> 17 : (($k1 & 0x7fffffff) >> 17) | 0x4000);
            $k1 = (((($k1 & 0xffff) * 0x1b873593) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0x1b873593) & 0xffff) << 16))) & 0xffffffff;
            $h1 ^= $k1;
            $h1 = $h1 << 13 | ($h1 >= 0 ? $h1 >> 19 : (($h1 & 0x7fffffff) >> 19) | 0x1000);
            $h1b = (((($h1 & 0xffff) * 5) + ((((($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000)) * 5) & 0xffff) << 16))) & 0xffffffff;
            $h1 = ((($h1b & 0xffff) + 0x6b64) + ((((($h1b >= 0 ? $h1b >> 16 : (($h1b & 0x7fffffff) >> 16) | 0x8000)) + 0xe654) & 0xffff) << 16));
        }
        $k1 = 0;
        switch ($remainder) {
            case 3:
                $k1 ^= $key[$i + 2] << 16;
            case 2:
                $k1 ^= $key[$i + 1] << 8;
            case 1:
                $k1 ^= $key[$i];
                $k1 = ((($k1 & 0xffff) * 0xcc9e2d51) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0xcc9e2d51) & 0xffff) << 16)) & 0xffffffff;
                $k1 = $k1 << 15 | ($k1 >= 0 ? $k1 >> 17 : (($k1 & 0x7fffffff) >> 17) | 0x4000);
                $k1 = ((($k1 & 0xffff) * 0x1b873593) + ((((($k1 >= 0 ? $k1 >> 16 : (($k1 & 0x7fffffff) >> 16) | 0x8000)) * 0x1b873593) & 0xffff) << 16)) & 0xffffffff;
                $h1 ^= $k1;
        }
        $h1 ^= $klen;
        $h1 ^= ($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000);
        $h1 = ((($h1 & 0xffff) * 0x85ebca6b) + ((((($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000)) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
        $h1 ^= ($h1 >= 0 ? $h1 >> 13 : (($h1 & 0x7fffffff) >> 13) | 0x40000);
        $h1 = (((($h1 & 0xffff) * 0xc2b2ae35) + ((((($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000)) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
        $h1 ^= ($h1 >= 0 ? $h1 >> 16 : (($h1 & 0x7fffffff) >> 16) | 0x8000);
        return $h1;
    }

}
